import cv2
import numpy as np

def crop_shadow(img_path, threshold=10):
    # 读取图像
    image = cv2.imread(img_path)
    # 转换为灰度图
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    # 使用阈值进行二值化
    _, binary = cv2.threshold(gray, threshold, 255, cv2.THRESH_BINARY)
    # 寻找轮廓
    contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    # 找到最大的轮廓
    cnt = max(contours, key=cv2.contourArea)
    # 计算轮廓的边界框
    x, y, w, h = cv2.boundingRect(cnt)
    # 裁剪图像
    crop_img = image[y:y+h, x:x+w]
    return crop_img

# 使用函数裁剪图像
cropped_image = crop_shadow('test.jpg')
# 显示裁剪后的图像
cv2.imwrite('Cropped.jpg', cropped_image)
cv2.waitKey(0)
cv2.destroyAllWindows()